package otherlogin

import (
	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	miniConfig "github.com/silenceper/wechat/v2/miniprogram/config"
	"github.com/slclub/glog"
	"github.com/slclub/go-tips/json"
	"github.com/spf13/viper"
	"os"
)

type ConfigData struct {
	AppID	string
	AppSecret	string
}

func GetWechatOpenID(wxCode string) (data any, err error) {
	//获取项目的执行路径
	path, err := os.Getwd()
	//导入配置文件
	viper.SetConfigType("yaml")
	viper.SetConfigFile(path+"/conf/conf.yaml")

	//读取配置文件
	err = viper.ReadInConfig()
	if err != nil {
		glog.Errorf("读取不到配置文件：",err.Error())
		return "Config Error", err
	}

	config := viper.Get("MiniProgramAccountConfig")
	if config == nil {
		glog.Errorf("未读取到小程序配置")
		return "MiniProgram Config Error", err
	}

	resByte, resByteErr := json.Marshal(config)
	if resByteErr != nil {
		glog.Errorf("JSON序列化失败," + resByteErr.Error())
		return "", err
	}

	var configMap ConfigData
	jsonRes := json.Unmarshal(resByte, &configMap)
	if jsonRes != nil {
		glog.Errorf("JSON反序列化失败" + jsonRes.Error())
		return "", err
	}

	wc := wechat.NewWechat()
	memory := cache.NewMemory()
	cfg := &miniConfig.Config{
		AppID:     configMap.AppID,
		AppSecret: configMap.AppSecret,
		Cache: memory,
	}

	mini := wc.GetMiniProgram(cfg)
	miniAuth := mini.GetAuth()
	wxSession, err := miniAuth.Code2Session(wxCode)

	return wxSession, err
}